package com.launch.carmanager.common.rx;

import com.launch.carmanager.common.expection.ApiException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.HttpException;
import rx.Subscriber;

/**
 * Created by ganquan on 2019/3/28 10:23
 */
public abstract class ApiSubscriber <T> extends Subscriber<T> {

    @Override
    public void onCompleted() {
    }

    /**
     * 处理非API异常
     */
    @Override
    public void onError(Throwable e) {
        String msg = e.getMessage();
        int code = -1;

        if (e instanceof HttpException) {
            code = ((HttpException) e).code();
            msg = "HTTP 异常" + code;

        } else if (e instanceof ConnectException) {
            msg = "连接异常";

        } else if (e instanceof SocketTimeoutException) {
            msg = "请求超时";

        } else if (e instanceof ApiException) {
            code = ((ApiException) e).getCode();

        } else {
            e.printStackTrace();
        }

        onFailure(code, msg);
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    public abstract void onSuccess(T t);

    public abstract void onFailure(int code, String msg);


}
